
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import {classTransformerUtils} from "@/utils/classTransformerUtils";
import plainToClass = classTransformerUtils.plainToClass;
import {validate} from "class-validator";

@Injectable()
export class CustomValidationPipe implements PipeTransform {
    async transform(value: any, { metatype }: ArgumentMetadata) {
        if (!metatype || !this.toValidate(metatype)) {
            return value;
        }
        const object = plainToClass(metatype, value);
        const errors = await validate(object);
        if (errors.length > 0) {
            const errStrLst = errors.map(err => err.constraints);
            const errList = [];
            errStrLst.forEach((err) =>{
                for (let errKey in err) {
                    errList.push([err[errKey]][0]);
                }
            });
            throw new BadRequestException(errList.join(','));
        }
        return value;
    }

    private toValidate(metatype: Function): boolean {
        const types: Function[] = [String, Boolean, Number, Array, Object];
        return !types.includes(metatype);
    }
}
